import { Controller } from 'egg';

const getOrgListRule = {
  parentId: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
};
const createOrgRule = {
  orgId: {
    type: 'string',
    required: true,
    allowEmpty: false,
  },
  orgName: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
  parentId: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
  orgManage: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
};
const removeOrgRule = {
  orgId: {
    type: 'string',
    required: true,
    allowEmpty: false,
  },
};
const saveOrgRule = {
  orgId: {
    type: 'string',
    required: true,
    allowEmpty: false,
  },
  orgName: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
  parentId: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
  orgManage: {
    type: 'string',
    required: false,
    allowEmpty: true,
  },
};

export default class Org extends Controller {
  async getOrgList() {
    const { ctx, service, logger } = this;
    const params = Object.assign({}, ctx.query, ctx.params);
    try {
      ctx.validate(getOrgListRule, params);
    } catch (err: any) {
      logger.error(new Error(err.code));
      ctx.body = ctx.response.paramError(err.errors);
      return false;
    }
    const result = await service.org.getOrgList(params);
    ctx.body = ctx.response.success(result);
  }
  async createOrg() {
    const { ctx, service, logger } = this;
    const params = Object.assign({}, ctx.request.body);
    try {
      ctx.validate(createOrgRule, params);
    } catch (err: any) {
      logger.error(new Error(err.code));
      ctx.body = ctx.response.paramError(err.errors);
      return false;
    }
    const result = await service.org.createOrg(params);
    ctx.body = ctx.response.success(result);
  }
  async removeOrg() {
    const { ctx, service, logger } = this;
    const params = Object.assign({}, ctx.request.body);
    try {
      ctx.validate(removeOrgRule, params);
    } catch (err: any) {
      logger.error(new Error(err.code));
      ctx.body = ctx.response.paramError(err.errors);
      return false;
    }
    const result = await service.org.removeOrg(params);
    ctx.body = ctx.response.success(result);
  }
  async saveOrg() {
    const { ctx, service, logger } = this;
    const params = Object.assign({}, ctx.request.body);
    try {
      ctx.validate(saveOrgRule, params);
    } catch (err: any) {
      logger.error(new Error(err.code));
      ctx.body = ctx.response.paramError(err.errors);
      return false;
    }
    const result = await service.org.saveOrg(params);
    ctx.body = ctx.response.success(result);
  }
}
